<template>
  <div>
    <!-- http-request 覆盖默认的上传行为，可以自定义上传的实现 -->
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="uploadImgFn"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="showProgress" class="progress" type="circle" :percentage="percentage" />
    </el-upload>
  </div>
</template>

<script>
// 引入
const COS = require('cos-js-sdk-v5')
// 实例化
const cos = new COS({
  SecretId: 'AKIDWrwlKcfU2JJ4YliPq0uYw3uWt0qPikV9',
  SecretKey: 'RcW9VXLtBe18zaw2sSmqeCVZNvEJ8h04'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      showProgress: false, // 控制进度条的显示与隐藏
      percentage: 0 // 进度条显示的进度
    }
  },
  methods: {
    uploadImgFn(files) {
      // 在文件开始上传的时候显示进度条
      this.showProgress = true
      if (files.file) {
        cos.putObject({
          Bucket: 'renzi-photo-1308159375', /* 存储桶名称*/
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: files.file.name, /* 文件名 */
          StorageClass: 'STANDARD',
          Body: files.file, // 上传文件对象
          onProgress: (progressData) => {
            // 将上传进度赋值给  percentage
            this.percentage = progressData.percent * 100
          }
        },
        // 使用箭头函数来解决this的指向问题
        (err, data) => {
          if (err === null) {
            // 拼接 imageUrl url 的路径
            this.imageUrl = 'https://' + data.Location
          }
          // 上传成功，显示进度条
          this.showProgress = false
        })
      }
    }
  }

}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<style lang="scss" scoped>
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>

